<template>
  <div class="data-format-manage p-2">
    <!-- 物模型协议 - 数据格式管理页面 -->
    <!-- 面包屑导航 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <div style="display: flex; align-items: center; justify-content: space-between;">
        <el-button type="primary" link @click="goBackToProtocol">
          <el-icon>
            <ArrowLeft />
          </el-icon>
          返回
        </el-button>
        <el-breadcrumb separator="/" class="breadcrumb">
          <el-breadcrumb-item>
            <el-button type="primary" link @click="goBackToProtocol">协议管理</el-button>
          </el-breadcrumb-item>
          <el-breadcrumb-item class="is-active">{{ protocolInfo.name }}</el-breadcrumb-item>
          <el-breadcrumb-item class="is-active">{{ '数据格式管理' }}</el-breadcrumb-item>
        </el-breadcrumb>
        <div></div>
      </div>
      <div style="margin-top: 8px; color: #666; font-size: 14px;">
        当前协议：{{ protocolInfo.name }} - 管理该协议下的数据格式定义
      </div>
    </el-card>

    <!-- 页面标题 -->
    <!-- <div class="page-header">
      <h2>数据格式管理</h2>
      <p>管理设备数据的格式定义，包括数据结构、解析规则等</p>
    </div> -->

    <!-- 搜索区域 -->
    <!-- <div class="search-section"> -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="数据格式名称" prop="name" label-width="100px">
          <el-input v-model="searchForm.name" placeholder="请输入数据格式名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="请求方式" prop="requestType">
          <el-select v-model="searchForm.requestType" placeholder="请选择请求方式" clearable style="width: 150px">
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <!-- </div> -->
    </el-card>


    <!-- 操作区域 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <!-- <div class="operation-section"> -->
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          新增
        </el-button>
        <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchDelete">
          <el-icon>
            <Delete />
          </el-icon>
          批量删除
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon>
            <Download />
          </el-icon>
          导出
        </el-button>
        <el-button @click="goBackToProtocol">
          <el-icon>
            <ArrowLeft />
          </el-icon>
          返回协议列表
        </el-button>
      </div>
      <!-- </div> -->
    </el-card>


    <!-- 数据表格 -->
    <!-- <div class="table-section"> -->
    <el-card shadow="hover" style="margin-bottom: 8px">

      <el-table v-loading="loading" :data="tableData" stripe border style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="数据格式ID" prop="dataformatId" width="120" />
        <el-table-column label="数据格式名称" prop="name" min-width="150" show-overflow-tooltip />
        <el-table-column label="请求方式" prop="requestType" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getRequestMethodType(row.requestType)">
              {{ row.requestType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="通信方向" prop="direction" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getCommunicationDirectionType(row.direction)">
              {{ getCommunicationDirectionText(row.direction) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="消息类型" prop="messageType" width="100" align="center" />
        <el-table-column label="数据格式类型" prop="dataformatType" width="120" align="center" />
        <el-table-column label="功能或方法名" prop="command" min-width="150" show-overflow-tooltip />
        <el-table-column label="接口相对路径" prop="url" min-width="200" show-overflow-tooltip />
        <el-table-column label="数据解析方式" prop="scriptType" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getScriptTypeTagType(row.scriptType)">
              {{ getScriptTypeText(row.scriptType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" icon="Edit" link @click="handleEdit(row)">
              修改
            </el-button>
            <el-button type="danger" icon="Delete" link @click="handleDelete(row)">
              删除
            </el-button>
            <el-button type="success" icon="Setting" link @click="handleConfigAttribute(row)">
              配置属性
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.size"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
      <!-- </div> -->
    </el-card>


    <!-- 新增/编辑弹窗 -->
    <DataFormatFormDialog v-model:visible="formDialogVisible" :title="currentFormData?.name ? '编辑数据格式' : '新增数据格式'"
      :data="currentFormData" :loading="loading" @submit="handleFormSubmit" @cancel="handleFormCancel" />
  </div>
</template>

<script setup lang="ts" name="DataFormatManage">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import {
  Search,
  Refresh,
  Plus,
  Download,
  Delete,
  ArrowLeft,
  Setting
} from '@element-plus/icons-vue'
import DataFormatFormDialog from './components/DataFormatFormDialog.vue'
// 移除远程API导入，改用本地模拟数据
// import { getDataFormatList, exportDataFormatList, deleteDataFormat, addDataFormat, updateDataFormat } from '@/api/IOT/protocolManage/dataFormatManage'
import type {
  DataFormatInfo,
  DataFormatQuery
} from '@/api/IOT/protocolManage/dataFormatManage/types'

// 模拟网络延迟（0~1500ms）
const delayRandom = (min = 200, max = 1500) => new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * (max - min + 1)) + min))

// 本地模拟的数据格式数据集
const allDataFormats = ref<DataFormatInfo[]>([
  { dataformatId: 'DF1001', name: '设备状态上报', requestType: 'POST', direction: 1, messageType: 'status', dataformatType: 'json', command: 'reportStatus', url: '/device/status', scriptType: 'JavaScript', protocolId: 'PV1001' },
  { dataformatId: 'DF1002', name: '设备心跳', requestType: 'POST', direction: 1, messageType: 'heartbeat', dataformatType: 'json', command: 'heartbeat', url: '/device/heartbeat', scriptType: 'JavaScript', protocolId: 'PV1001' },
  { dataformatId: 'DF1003', name: '下发控制命令', requestType: 'POST', direction: 0, messageType: 'control', dataformatType: 'json', command: 'control', url: '/device/control', scriptType: 'Groovy', protocolId: 'PV1001' },
  { dataformatId: 'DF1004', name: '数据同步', requestType: 'GET', direction: 0, messageType: 'sync', dataformatType: 'json', command: 'sync', url: '/device/sync', scriptType: 'Groovy', protocolId: 'PV1002' }
])

// 路由
const router = useRouter()
const route = useRoute()

// 协议信息
const protocolInfo = reactive({
  id: '',
  name: '',
  productId: '',
  productName: '',
  categoryId: '',
  categoryName: ''
})

// 初始化路由参数
onMounted(() => {
  const { protocolId, protocolName } = route.query as Record<string, string>
  protocolInfo.id = protocolId || ''
  protocolInfo.name = protocolName || ''
  // 将协议ID写入默认搜索条件
  searchForm.protocolId = protocolInfo.id
  // 初始加载
  handleSearch()
})

// 返回协议列表
const goBackToProtocol = () => {
  router.push({ path: '/iot/protocol/protocol-list' })
}

// 响应式数据
const loading = ref(false)
const formDialogVisible = ref(false)
const currentFormData = ref<DataFormatInfo | undefined>()

// 搜索表单
const searchForm = reactive<DataFormatQuery>({
  name: '',
  requestType: '',
  protocolId: '',
  protocolVersionId: ''
})

// 表格数据
const tableData = ref<DataFormatInfo[]>([])
const selectedRows = ref<DataFormatInfo[]>([])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 工具函数
const getRequestMethodType = (method?: string) => {
  const typeMap: Record<string, string> = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'danger'
  }
  return typeMap[method || ''] || 'info'
}

const getCommunicationDirectionType = (direction?: number) => {
  const typeMap: Record<number, string> = {
    0: 'primary',
    1: 'success'
  }
  return typeMap[direction ?? -1] || 'info'
}

const getCommunicationDirectionText = (direction?: number) => {
  const textMap: Record<number, string> = {
    0: '请求',
    1: '响应'
  }
  return textMap[direction ?? -1] || '-'
}

const getScriptTypeTagType = (scriptType?: string) => {
  const typeMap: Record<string, string> = {
    'Groovy': 'warning',
    'JavaScript': 'success'
  }
  return typeMap[scriptType || ''] || 'info'
}

const getScriptTypeText = (scriptType?: string) => {
  if (!scriptType) return '系统默认'
  return scriptType
}



// 事件处理函数
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    requestType: '',
    protocolId: protocolInfo.id,
    protocolVersionId: protocolInfo.id
  })
  handleSearch()
}

const handleAdd = () => {
  console.log('protocolInfo', protocolInfo)
  currentFormData.value = {
    protocolVersionId: protocolInfo.id
  } as DataFormatInfo
  formDialogVisible.value = true
}

const handleEdit = (row: DataFormatInfo) => {
  currentFormData.value = { ...row, protocolVersionId: row.protocolId }
  formDialogVisible.value = true
}

const handleConfigAttribute = (row: DataFormatInfo) => {
  // 跳转到配置属性管理页面，传递相关参数（路径与路由模块保持一致）
  router.push({
    path: '/iot/protocol/config-attribute',
    query: {
      protocolVersionId: protocolInfo.id,
      formatId: row.dataformatId,
      formatName: row.name,
      protocolId: protocolInfo.id,
      protocolName: protocolInfo.name
    }
  })
}

// 删除（单条）使用本地模拟数据
const handleDelete = async (row: DataFormatInfo) => {
  try {
    await ElMessageBox.confirm(`确定要删除数据格式\"${row.name}\"吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await delayRandom()
    allDataFormats.value = allDataFormats.value.filter(df => String(df.dataformatId) !== String(row.dataformatId))
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除（本地模拟）
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条数据格式吗？`, '批量删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await delayRandom()
    const idsToDelete = selectedRows.value.map(row => String(row.dataformatId))
    allDataFormats.value = allDataFormats.value.filter(df => !idsToDelete.includes(String(df.dataformatId)))
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 导出（CSV，本地数据）
const handleExport = async () => {
  await delayRandom()
  const headers = ['数据格式ID', '数据格式名称', '请求方式', '通信方向', '消息类型', '数据格式类型', '功能/方法名', '接口相对路径', '解析脚本类型']
  const rows = tableData.value.map(row => [row.dataformatId, row.name, row.requestType, getCommunicationDirectionText(row.direction), row.messageType, row.dataformatType, row.command, row.url, row.scriptType || '系统默认'])
  const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `数据格式列表_${new Date().getTime()}.csv`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
  ElMessage.success('导出成功')
}

// 表单提交（新增/修改，本地模拟）
const handleFormSubmit = async (formData: DataFormatInfo) => {
  try {
    loading.value = true
    await delayRandom()
    if (formData.dataformatId) {
      const idx = allDataFormats.value.findIndex(df => String(df.dataformatId) === String(formData.dataformatId))
      if (idx !== -1) {
        allDataFormats.value[idx] = { ...allDataFormats.value[idx], ...formData }
      } else {
        ElMessage.error('未找到该数据格式')
        return
      }
      ElMessage.success('修改成功')
    } else {
      const newId = 'DF' + String(Math.max(0, ...allDataFormats.value.map(df => Number(String(df.dataformatId).replace(/^DF/, '')))) + 1).padStart(4, '0')
      const newItem: DataFormatInfo = { ...formData, dataformatId: newId, protocolId: protocolInfo.id }
      allDataFormats.value.unshift(newItem)
      ElMessage.success('新增成功')
    }
    formDialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    loading.value = false
  }
}

// 加载列表（使用本地模拟数据）
const loadData = async () => {
  loading.value = true
  await delayRandom()
  // 过滤：按协议ID与搜索条件
  let filtered = allDataFormats.value.filter(df => String(df.protocolId) === String(protocolInfo.id))
  if (searchForm.name) {
    const kw = String(searchForm.name).toLowerCase()
    filtered = filtered.filter(df => String(df.name).toLowerCase().includes(kw))
  }
  if (searchForm.requestType) {
    filtered = filtered.filter(df => String(df.requestType) === String(searchForm.requestType))
  }
  // 分页
  const start = (pagination.page - 1) * pagination.size
  const end = start + pagination.size
  tableData.value = allDataFormats.value
  pagination.total = filtered.length
  loading.value = false
}
// loadData()
</script>

<style scoped>
.data-format-manage {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-section {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  width: 100%;
}

.operation-section {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.operation-buttons {
  display: flex;
  gap: 8px;
}

.table-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}

.mr-1 {
  margin-right: 4px;
}

.breadcrumb {
  display: flex;
}
</style>